<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\course\UserCoupon;
use app\admin\model\Third;
use app\common\controller\Api;
use app\common\model\order\PayLog;
use think\Db;

/**
 * 优惠券模块
 * @ApiWeigh (60)
 */
class Coupon extends Api
{
    protected $noNeedLogin = ["getCouponList"];
    protected $noNeedRight = ['*'];

    /**
     * 优惠券列表
     * @ApiWeigh (100)
     * @ApiMethod   (POST)
     *
     * @ApiParams   (name="type", type="string", required=true, description="类型：free:免费；pay:付费")
     * @ApiReturnParams   (name="title", type="string", required=true, description="优惠券名称")
     * @ApiReturnParams   (name="type", type="string", required=true, description="类型：free:免费；pay:付费")
     * @ApiReturnParams   (name="money", type="string", required=true, description="满足金额")
     * @ApiReturnParams   (name="reduction_money", type="string", required=true, description="减免金额")
     * @ApiReturnParams   (name="coupon_money", type="string", required=true, description="付费类型优惠券价格")
     * @ApiReturnParams   (name="surplus_num", type="string", required=true, description="剩余数量")
     * @ApiReturnParams   (name="day", type="string", required=true, description="有效期")
     */
    public function getCouponList(){
        $couponModel = new \app\admin\model\course\Coupon();
        $condition = [];
        $type = $this->request->post("type");
        if($type){
            $condition['type'] = $type;
        }

        try {
            $courseList = $couponModel->getList($this->auth->getUser(),$condition);
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }

        $this->success("查询成功", $courseList);
    }

    /**
     * 领取优惠券
     * @ApiWeigh (99)
     * @ApiMethod   (POST)
     * @ApiParams   (name="id", type="integer", required=true, description="优惠券id")
     */
    public function receiveCoupon(){
        //设置缓存锁
        $id = $this->request->post("id");
        $couponModel = new \app\admin\model\course\Coupon();

        try {
            $info = $couponModel->getInfo([
                "id"=>$id,
                "type"=>$couponModel::TYPE_FREE,
            ]);
            //判断是否领取过
            $is_receive = $info->checkReceive($this->auth->getUser());
            if($is_receive){
                exception("当前优惠券已经领取过");
            }
            $info->sendCoupon($this->auth->id);
        }catch (\Exception $exception){
            $this->error($exception->getMessage());
        }
        $this->success("领取成功");

    }

    /**
     * 购买优惠券
     * @ApiWeigh (98)
     * @ApiMethod (POST)
     *
     * @ApiParams   (name="id", type="string",  description="优惠券id")
     */
    public function buyCoupon(){
        $id = $this->request->post("id");
//        $pay_from = $this->request->post("pay_from");
        $pay_from = "miniapp";
//        $pay_type = $this->request->post("pay_type");
        $pay_type = "wechat";
        if(!in_array($pay_from, ["miniapp", "app"])){
            $this->error("支付类型错误");
        }
        if(!in_array($pay_type, ["wechat", "alipay"])){
            $this->error("支付方式错误");
        }
        $payLog = new PayLog();
        $aliPay = "";
        $wechatPay = [];
        $order_sn = $payLog->getOrderSn(PayLog::BUY_COUPON);

        $couponModel = new \app\admin\model\course\Coupon();

        Db::startTrans();
        try {
            $info = $couponModel->getInfo([
                "id"=>$id,
                "type"=>$couponModel::TYPE_PAY,
            ]);
            $is_receive = $info->checkReceive($this->auth->getUser());
            if($is_receive){
                exception("当前优惠券已经购买过了");
            }
            $extend = [
                "data_id" => $info["id"]
            ];
            switch ($pay_type){
                case "wechat":
                    //微信支付
                    $params = [
                        'type'         => $pay_type,
                        'orderid' => $order_sn,
                        'title'        => "购买优惠券".$info["title"],
                        'amount'       => $info["coupon_money"],
                        'method'       => $pay_from,
                        'notifyurl'    => $this->request->domain() . "/api/common/notify/type/" . $pay_type . "/from/" . $pay_from,
                        'returnurl'    => $this->request->domain(),
                    ];
                    if($pay_from == "miniapp"){
                        $openid = Third::where("user_id",$this->auth->id)->where("platform","wechatMiniApp")->value("openid");
                        if(!$openid){
                            exception("当前小程序用户没有小程序id,请联系管理员");
                        }
                        $params["openid"] = $openid;
                    }

                    $wechatPay =  Service::submitOrder($params);

                    $payLog->createPayLog($this->auth->getUser(), $order_sn, $info["coupon_money"], $pay_from, $pay_type, $extend);
                    break;
                case "alipay":
                    //支付宝支付
                    $params = [
                        'type'         => $pay_type,
                        'orderid' => $order_sn,
                        'title'        => "购买优惠券".$info["title"],
                        'amount'       => $info["coupon_money"],
                        'method'       => $pay_from,
                        'notifyurl'    => $this->request->domain() . "/api/common/notify/type/" . $pay_type. "/from/" . $pay_from,
                        'returnurl'    => $this->request->domain(),
                    ];
                    $aliPay =  Service::submitOrder($params);
                    $payLog->createPayLog($this->auth->getUser(), $order_sn, $info["coupon_money"], $pay_from, $pay_type, $extend);
                    break;
            }
            $res = [
                "wechatPay" => $wechatPay,
                "aliPay" => $aliPay,
            ];
            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
            $this->error($exception->getMessage());

        }
        $this->success("下单成功", $res);
    }

    /**
     * 获取会员优惠券
     * @ApiMethod   (POST)
     * @ApiParams   (name="page", type="integer", required=true, description="页码")
     * @ApiParams   (name="status", type="integer", required=true, description="状态：1:未使用；2：已使用;3:已过期")
     * @ApiParams   (name="money", type="integer", required=true, description="订单金额")
     * @ApiReturnParams   (name="title", type="string", required=true, description="优惠券名称")
     * @ApiReturnParams   (name="type", type="string", required=true, description="类型：free:免费；pay:付费")
     * @ApiReturnParams   (name="money", type="string", required=true, description="满足金额")
     * @ApiReturnParams   (name="reduction_money", type="string", required=true, description="减免金额")
     * @ApiReturnParams   (name="coupon_money", type="string", required=true, description="付费类型优惠券价格")
     * @ApiReturnParams   (name="surplus_num", type="string", required=true, description="剩余数量")
     * @ApiReturnParams   (name="end_time_text", type="string", required=true, description="结束时间")
     */
    public function getUserCouponList()
    {
        $status = $this->request->post("status");
        $money = $this->request->post("money");
        $userCoupon = new UserCoupon();
        $coupon = new \app\admin\model\course\Coupon();
        $where = [
            "user_coupon.user_id" => $this->auth->id
        ];
        if($money){
            $where['user_coupon.money'] = ["<=", $money];
        }
        switch ($status){
            case 3:
                $where["user_coupon.status"] = $coupon::STATUS_SEND;
                $where["user_coupon.end_time"] = ["<",time()];
                break;
            default:
                $where['user_coupon.status'] = $status;
                $where['user_coupon.start_time'] =  ["<",time()];
                $where['user_coupon.end_time'] = [">",time()];
        }

        $list = $userCoupon
            ->with(['coupon'])
            ->where($where)
            ->order("id", "desc")
            ->paginate();
        foreach ($list as $row) {
            $row->getRelation('coupon')->visible(['title']);
        }
        $this->success("查询成功", $list);
    }

}
